/*
 * Copyright (c) 2010-2015 meituan.com
 * All rights reserved.
 * 
 */
package com.ferry.lock.util;

/**
 * 格式化lock 名称
 */
public class LockNameUtil {
    private LockNameUtil() {
    }

    public static void validateZkPath(String lockName) throws IllegalArgumentException {

        baseValidate(lockName);

        String reason = null;
        char lastc = 47;
        char[] chars = lockName.toCharArray();

        for (int i = 1; i < chars.length; ++i) {
            char c = chars[i];
            if (c == 0) {
                reason = "不允许空字符串:" + i;
                break;
            }

            if (c == 47 && lastc == 47) {
                reason = "不允许空字符串:" + i;
                break;
            }

            if (c == 46 && lastc == 46) {
                if (chars[i - 2] == 47 && (i + 1 == chars.length || chars[i + 1] == 47)) {
                    reason = "不允许相关字符串:" + i;
                    break;
                }
            } else if (c == 46) {
                if (chars[i - 1] == 47 && (i + 1 == chars.length || chars[i + 1] == 47)) {
                    reason = "不允许相关字符串:" + i;
                    break;
                }
            } else if (c > 0 && c < 31 || c > 127 && c < 159 || c > '\ud800' && c < '\uf8ff' || c > '\ufff0' && c < '\uffff') {
                reason = "非法字符串: " + i;
                break;
            }

            lastc = chars[i];
        }

        if (reason != null) {
            throw new IllegalArgumentException("Invalid lockName string \"" + lockName + "\" caused by " + reason);
        }

    }


    public static void validateRedisKey(String lockName) throws IllegalArgumentException {
        baseValidate(lockName);
    }

    /**
     * 基础检查
     * @param lockName
     */
    private static void baseValidate(String lockName) {
        if (lockName == null) {
            throw new IllegalArgumentException("锁名称不能为空");
        } else if (lockName.length() == 0) {
            throw new IllegalArgumentException("所名称长度必须大于0");
        }
    }
}
